package top.frsf.autocodegen.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import top.frsf.autocodegen.controller.dto.CodeGenDTO;
import top.frsf.autocodegen.entity.AutoField;
import top.frsf.autocodegen.entity.AutoTable;
import top.frsf.autocodegen.meta.RootFileItem;
import top.frsf.autocodegen.meta.TemplateNameEnum;
import top.frsf.autocodegen.service.IAutoFieldService;
import top.frsf.autocodegen.service.IAutoTableService;
import top.frsf.autocodegen.service.ICodeGeneratorService;
import top.frsf.autocodegen.utils.EnvConfigUtil;
import top.frsf.autocodegen.utils.Result;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author FRSF
 * @date 2024/7/31 22:18
 * @desc 代码生成接口
 */
@Tag(name = "3 - 代码生成")
@RestController
@RequestMapping("/codeGen")
public class CodeGenController {

    @Resource
    private ICodeGeneratorService codeGeneratorService;


    @GetMapping("/template")
    @Operation(summary = "获取模板列表")
    public Result<List<HashMap<String, Object>>> getTemplateList() {
        TemplateNameEnum[] values = TemplateNameEnum.values();
        List<HashMap<String, Object>> list = new ArrayList<>(values.length);
        for (TemplateNameEnum value : values) {
            HashMap<String, Object> map = new HashMap<>(2);
            map.put("name", value.getName());
            map.put("value", value.getValue());
            list.add(map);
        }
        return Result.success(list);
    }

    @Deprecated
    @GetMapping("/desktop")
    @Operation(summary = "生成代码文件到Desktop")
    public Result<String> genCodeDesktop(@Validated CodeGenDTO dto) {
        codeGeneratorService.genCodeOnDesktop(dto);
        return Result.success("导出成功");
    }

    @GetMapping("/browser")
    @Operation(summary = "生成代码Zip到浏览器")
    public ResponseEntity<byte[]> genCodeZip(@Validated CodeGenDTO dto) throws IOException, TemplateException {
       return codeGeneratorService.genCodeOnBrowser(dto);
    }

}
